package club.tclyq.good_time.document.service;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author tanchong
 * Create Date: 2019/2/26
 */
@Service
public class ExportDocumentService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExportDocumentService.class);
    private String NEW_WINDOWS = "document/Windows2008系列日志采集器安装手册.zip";
    private String OLD_WINDOWS = "document/Windows2003系列日志采集器安装手册.zip";
    private String CENTOS = "document/RedHat(Centos)操作系统日志采集器安装手册.docx";
    private String UBUNTU = "document/Ubuntu操作系统日志采集器安装手册.docx";

    public void exportHelpDocument(HttpServletResponse response, HttpServletRequest request, String flag) throws FileNotFoundException {
        LOGGER.info("flag {}",flag);
        Integer value = Integer.valueOf(flag);
        var path = checkFlag(value);
        LOGGER.info("path ::: " +
                "{}",path);
        try {
            var file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + path);
            var inputStream = new FileInputStream(file);
            var outputStream = response.getOutputStream();
            response.setCharacterEncoding(request.getCharacterEncoding());
            String[] split = path.split("/");
            response.setHeader("Content-Disposition",
                    "attachment; filename="+ URLEncoder.encode(split[1] , "UTF-8"));
            response.setContentType("application/zip");
            IOUtils.copy(inputStream, outputStream);
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private String checkFlag(int flag){
        LOGGER.info("flag is {}",flag);
        switch (flag){
            case 0:
                return NEW_WINDOWS;
            case 1:
                return OLD_WINDOWS;
            case 2:
                return CENTOS;
            case 3:
                return UBUNTU;

        }
        return null;
    }
}
